import { isArray } from 'lodash';
import { getConfig } from 'ee-core/config';
import { wallpaperService } from '../service/wallpapper';
import CoreElectronWindow from 'ee-core/electron/window';

class WallpaperController {
  reloadWindow() {
    const mainWindow = CoreElectronWindow.getMainWindow();
    mainWindow.webContents.reload();
  }

  /**
   * 检测http服务是否开启
   */
  checkHttpServer(): { enable: boolean; server: string } {
    const httpConfig = getConfig().httpServer;
    if (
      !httpConfig ||
      !('enable' in httpConfig) ||
      !('protocol' in httpConfig) ||
      !('host' in httpConfig) ||
      !('port' in httpConfig)
    ) {
      return { enable: false, server: '' };
    }
    const { enable, protocol, host, port } = httpConfig;
    const url = `${protocol}${host}:${port}`;
    console.log('[checkHttpServer] url:', url);
    const data = {
      enable: enable,
      server: url
    };
    return data;
  }

  /**
   * 上传文件
   * @args 是前端传的参数
   * @ctx 是koa的ctx对象
   */
  async addFile(args: any, ctx: any) {
    const file = ctx.request.files.file;
    const tags = args.tags;
    try {
      if (isArray(file)) {
        for (const f of file) {
          await wallpaperService.addFile(f, tags);
        }
      } else {
        await wallpaperService.addFile(file, tags);
      }
      return { code: 200, message: `文件保存成功！` };
    } catch (e: any) {
      return { code: 500, message: e.message };
    }
  }

  /**
   * 查询文件
   */
  getFile(params) {
    return {
      code: 200,
      result: wallpaperService.queryFile(params)
    };
  }

  /**
   * 删除文件
   */
  async deleteFile({ id }) {
    if (!id) {
      return { code: 500, result: null, message: '参数id不能为空！' };
    }

    try {
      // 删除文件以及映射关系
      wallpaperService.deleteFile(id);
      return { code: 200, message: '删除成功！' };
    } catch (e: any) {
      return { code: 500, message: e.message };
    }
  }

  /**
   * 查询所有分类映射关系
   */
  queryAllTag() {
    return {
      code: 200,
      result: wallpaperService.queryAllTag()
    };
  }

  /**
   * 添加分类映射关系
   */
  addTag({ tag }) {
    if (!tag) {
      return {
        code: 500,
        message: '参数tag不能为空！'
      };
    }

    return {
      code: 200,
      result: wallpaperService.addTag(tag)
    };
  }

  /**
   * 删除分类映射关系
   */
  async deleteTag({ id }) {
    if (!id) {
      return {
        code: 500,
        message: '参数id不能为空！'
      };
    }

    // 查询该id是否关联文件，并返回关联的文件
    const hasRelatesFiles = await wallpaperService.queryFile({
      tags: id
    });
    if (hasRelatesFiles?.length) {
      return {
        code: 501,
        message: '参数id存在关联文件！',
        result: hasRelatesFiles
      };
    }

    return {
      code: 200,
      result: wallpaperService.deleteTag(id)
    };
  }
}

WallpaperController.toString = () => '[class WallpaperController]';

export default WallpaperController;
